package com.disc.open189;
import com.alibaba.fastjson.JSONObject;
import com.disc.baidu.BaiduUser;
import com.disc.common.Constant;
import com.disc.common.DiscResponse;
import com.disc.util.HttpUtil;
import com.disc.util.RegexUtil;
import org.apache.http.NameValuePair;
import org.apache.http.client.CookieStore;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.util.*;


public class TianYiLogin {

    public CookieStore cookieStore =  new BasicCookieStore();

    public CloseableHttpClient httpclient;

    public String type = "TIANYI";

    public Date createTime;


    /**
     * 初始化httpclient
     * @throws KeyStoreException
     * @throws NoSuchAlgorithmException
     * @throws KeyManagementException
     */
    public  TianYiLogin() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException
    {
        httpclient =  HttpClients.custom().useSystemProperties().setConnectionManager(HttpUtil.getSSLNoCheckConnectionManager()).setDefaultCookieStore(cookieStore).build();
    }

    /**
     * 初始化cookie
     */
    public void initCookie()
    {
        HttpUtil.createHttpGet(Constant.TIANYI_MAIN,httpclient);
    }

    /**
     * 获取captchaToken
     */
    public  Map<String,String> getCaptchaToken() throws  Exception
    {
        Map<String,String> resultMap = new HashMap<>();
        String result =  HttpUtil.createHttpGet(Constant.TIANYI_LOGIN_PAGE,httpclient);
        String returnUrl = RegexUtil.findAll(result,"returnUrl = '(.*?)'",1).get(0);
        Document doc = Jsoup.parse(result);
        resultMap.put("captchaToken",doc.select("input[name=captchaToken]").val());
        resultMap.put("returnUrl",returnUrl);
        return resultMap;
    }


    public DiscResponse login(Map<String,String> resultMap, BaiduUser baiduUser) throws Exception {
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("appKey","cloud"));
        nvps.add(new BasicNameValuePair("accountType", "01"));
        nvps.add(new BasicNameValuePair("userName",baiduUser.getAccount()));
        nvps.add(new BasicNameValuePair("password",baiduUser.getPassword()));
        nvps.add(new BasicNameValuePair("validateCode", baiduUser.getVerificationCode()));
        nvps.add(new BasicNameValuePair("captchaToken", resultMap.get("captchaToken")));
        nvps.add(new BasicNameValuePair("returnUrl", resultMap.get("returnUrl")));
        nvps.add(new BasicNameValuePair("mailSuffix", "@189.cn"));
        nvps.add(new BasicNameValuePair("dynamicCheck", "FALSE"));
        nvps.add(new BasicNameValuePair("clientType", "10010"));
        nvps.add(new BasicNameValuePair("cb_SaveName", "0"));
        String content =   HttpUtil.createHttpPost(Constant.TIANYI_LOGIN_URL,nvps,httpclient);
        JSONObject jsonObject = JSONObject.parseObject(content);
        DiscResponse discResponse = new DiscResponse();
        discResponse.setCode(jsonObject.getString("result"));
        discResponse.setMessage(jsonObject.getString("msg"));
        if("0".equals(jsonObject.getString("result")) && "登录成功".equals(jsonObject.getString("msg")))
        {
           String redirect_html = HttpUtil.createHttpGet(jsonObject.getString("toUrl"),httpclient);
           String redirect_url = RegexUtil.findAll(redirect_html,"redirect_url = '(.*?)'",1).get(0);
            if("/main.action".equals(redirect_url))
            {
                initCookie();
            }
        }
        return discResponse;
    }

}
